from flask_mail import Message
from flask import current_app, render_template
from threading import Thread
from app import mail

# email文件要放在app目录下

def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)

def send_email(to, subject, template, **kwargs):
    app = current_app._get_current_object()  # 发送邮件要在另一个线程运行，这里要获取app的实例，不能直接使用current_app
    msg = Message(app.config['FLASKY博客邮件主题前缀']+subject, sender=app.config['FLASKY邮件发送者'], recipients=[to])
    msg.body = render_template(template+'.txt', **kwargs)
    msg.html = render_template(template+'.html', **kwargs)
    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()
    return thr